// 和用户相关的状态管理

import { createSlice } from '@reduxjs/toolkit'
import { removeToken } from '../../utils/token'
import { getProfileAPI, loginAPI } from '../../apis/user'

const userStore = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token: localStorage.getItem('token') || '',
    userInfo: {}
  },
  // 同步修改方法
  reducers: {
    setToken (state, action) {
      state.token = action.payload
      localStorage.setItem('token', action.payload)
    },
    setUserInfo (state, action) {
      state.userInfo = action.payload
    },
    cleanUserInfo(state){
      state.userInfo = {}
      state.token = ''
      removeToken()
    }
  }
})

// 解构出actionCreater

const { setToken, setUserInfo, cleanUserInfo } = userStore.actions

// 获取reducer函数

const userReducer = userStore.reducer

// 登录获取token异步方法封装
const loginToken = loginForm => {
  return async dispatch => {
    const res = await loginAPI(loginForm)
    dispatch(setToken(res.data.token))
  }
}

// 用户信息异步方法
const getUserInfo = () => {
  return async dispatch => {
    const res = await getProfileAPI()
    dispatch(setUserInfo(res.data))
  }
}

export { loginToken, setToken, getUserInfo, cleanUserInfo}

export default userReducer
